home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 1865 / 1865.xpi / chrome / adblockplus.jar / content / utils.js < prev   
Text File  |  2010-01-07  |  7KB  |  261 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Adblock Plus.
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Wladimir Palant.
  18.  * Portions created by the Initial Developer are Copyright (C) 2006-2009
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *
  23.  * ***** END LICENSE BLOCK ***** */
  24.  
  25. /**
  26.  * @fileOverview Utility functions and classes.
  27.  * This file is included from AdblockPlus.js.
  28.  */
  29.  
  30. var threadManager = Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager);
  31.  
  32. // String service
  33. var stringService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
  34. var strings = stringService.createBundle("chrome://adblockplus/locale/global.properties");
  35. abp.getString = function(name) {
  36.     return strings.GetStringFromName(name);
  37. };
  38.  
  39. // Retrieves the window object for a node or returns null if it isn't possible
  40. function getWindow(node) {
  41.     if (node && node.nodeType != Node.DOCUMENT_NODE)
  42.         node = node.ownerDocument;
  43.  
  44.     if (!node || node.nodeType != Node.DOCUMENT_NODE)
  45.         return null;
  46.  
  47.     return node.defaultView;
  48. }
  49.  
  50. // Unwraps jar:, view-source: and wyciwyg: URLs, returns the contained URL
  51. function unwrapURL(url) {
  52.     if (!(url instanceof Ci.nsIURI))
  53.         url = makeURL(url);
  54.  
  55.     try
  56.     {
  57.         switch (url.scheme)
  58.         {
  59.             case "view-source":
  60.                 return unwrapURL(url.path);
  61.             case "wyciwyg":
  62.                 return unwrapURL(url.path.replace(/^\/\/\d+\//, ""));
  63.             case "jar":
  64.                 return unwrapURL(url.QueryInterface(Ci.nsIJARURI).JARFile);
  65.             default:
  66.                 if (url instanceof Ci.nsIURL && url.ref)
  67.                     return makeURL(url.spec.replace(/#.*/, ""));
  68.                 else
  69.                     return url;
  70.         }
  71.     }
  72.     catch (e) { return url; }
  73. }
  74. abp.unwrapURL = unwrapURL;
  75.  
  76. // Returns an nsIURI for given url
  77. function makeURL(url) {
  78.     try
  79.     {
  80.         return ioService.newURI(url, null, null);
  81.     }
  82.     catch (e) {
  83.         return null;
  84.     }
  85. }
  86. abp.makeURL = makeURL;
  87.  
  88. // Generates a click handler for object tabs
  89. function generateClickHandler(wnd, data) {
  90.     return function(event) {
  91.         event.preventDefault();
  92.         wnd.openDialog("chrome://adblockplus/content/ui/composer.xul", "_blank", "chrome,centerscreen,resizable,dialog=no,dependent", wnd, data); 
  93.     }
  94. }
  95.  
  96. // Creates a tab above/below the new object node
  97. function addObjectTab(wnd, node, data, tab)
  98. {
  99.     if (!node.parentNode)
  100.         return;
  101.  
  102.     // Click event handler
  103.     tab.setAttribute("href", data.location);
  104.     tab.setAttribute("class", policy.objtabClass);
  105.     tab.addEventListener("click", generateClickHandler(wnd, data), false);
  106.  
  107.     // Insert tab into the document
  108.     if (node.nextSibling)
  109.         node.parentNode.insertBefore(tab, node.nextSibling);
  110.     else
  111.         node.parentNode.appendChild(tab);
  112. }
  113.  
  114. /**
  115.  * Posts an action to the event queue of the current thread to run it
  116.  * asynchronously. Any additional parameters to this function are passed
  117.  * as parameters to the callback.
  118.  */
  119. function runAsync(/**Function*/ callback, /**Object*/ thisPtr)
  120. {
  121.     let params = Array.prototype.slice.call(arguments, 2);
  122.     let runnable = {
  123.         run: function()
  124.         {
  125.             callback.apply(thisPtr, params);
  126.         }
  127.     };
  128.     threadManager.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL);
  129. }
  130. abp.runAsync = runAsync;
  131.  
  132. /**
  133.  * Gets the DOM window associated with a particular request (if any).
  134.  */
  135. function getRequestWindow(/**nsIChannel*/ channel) /**nsIDOMWindow*/
  136. {
  137.     let callbacks = [];
  138.     if (channel.notificationCallbacks)
  139.         callbacks.push(channel.notificationCallbacks);
  140.     if (channel.loadGroup && channel.loadGroup.notificationCallbacks)
  141.         callbacks.push(channel.loadGroup.notificationCallbacks);
  142.  
  143.     for each (let callback in callbacks)
  144.     {
  145.         try {
  146.             // For Gecko 1.9.1
  147.             return callback.getInterface(Ci.nsILoadContext).associatedWindow;
  148.         } catch(e) {}
  149.  
  150.         try {
  151.             // For Gecko 1.9.0
  152.             return callback.getInterface(Ci.nsIDOMWindow);
  153.         } catch(e) {}
  154.     }
  155.  
  156.     return null;
  157. }
  158.  
  159. // Returns plattform dependent line break string
  160. var lineBreak = null;
  161. function getLineBreak() {
  162.     if (lineBreak == null) {
  163.         // HACKHACK: Gecko doesn't expose NS_LINEBREAK, try to determine
  164.         // plattform's line breaks by reading prefs.js
  165.         lineBreak = "\n";
  166.         try {
  167.             var dirService = Cc["@mozilla.org/file/directory_service;1"].createInstance(Ci.nsIProperties);
  168.             var prefFile = dirService.get("PrefF", Ci.nsIFile);
  169.             var inputStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
  170.             inputStream.init(prefFile, 0x01, 0444, 0);
  171.  
  172.             var scriptableStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
  173.             scriptableStream.init(inputStream);
  174.             var data = scriptableStream.read(1024);
  175.             scriptableStream.close();
  176.  
  177.             if (/(\r\n?|\n\r?)/.test(data))
  178.                 lineBreak = RegExp.$1;
  179.         } catch (e) {}
  180.     }
  181.     return lineBreak;
  182. }
  183. abp.getLineBreak = getLineBreak;
  184.  
  185. // Removes unnecessary whitespaces from filter
  186. function normalizeFilter(text) {
  187.     if (!text)
  188.         return text;
  189.  
  190.     // Remove line breaks and such
  191.     text = text.replace(/[^\S ]/g, "");
  192.  
  193.     if (/^\s*!/.test(text)) {
  194.         // Don't remove spaces inside comments
  195.         return text.replace(/^\s+/, "").replace(/\s+$/, "");
  196.     }
  197.     else if (Filter.elemhideRegExp.test(text)) {
  198.         // Special treatment for element hiding filters, right side is allowed to contain spaces
  199.         /^(.*?)(#+)(.*)$/.test(text);   // .split(..., 2) will cut off the end of the string
  200.         var domain = RegExp.$1;
  201.         var separator = RegExp.$2;
  202.         var selector = RegExp.$3;
  203.         return domain.replace(/\s/g, "") + separator + selector.replace(/^\s+/, "").replace(/\s+$/, "");
  204.     }
  205.     else
  206.         return text.replace(/\s/g, "");
  207. }
  208. abp.normalizeFilter = normalizeFilter;
  209.  
  210. /**
  211.  * Generates filter subscription checksum.
  212.  *
  213.  * @param {Array of String} lines filter subscription lines (with checksum line removed)
  214.  * @return {String} checksum or null
  215.  */
  216. function generateChecksum(lines)
  217. {
  218.     let stream = null;
  219.     try
  220.     {
  221.         // Checksum is an MD5 checksum (base64-encoded without the trailing "=") of
  222.         // all lines in UTF-8 without the checksum line, joined with "\n".
  223.  
  224.         let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
  225.         converter.charset = "UTF-8";
  226.         stream = converter.convertToInputStream(lines.join("\n"));
  227.  
  228.         let hashEngine = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
  229.         hashEngine.init(hashEngine.MD5);
  230.         hashEngine.updateFromStream(stream, stream.available());
  231.         return hashEngine.finish(true).replace(/=+$/, "");
  232.     }
  233.     catch (e)
  234.     {
  235.         return null;
  236.     }
  237.     finally
  238.     {
  239.         if (stream)
  240.             stream.close();
  241.     }
  242. }
  243. abp.generateChecksum = generateChecksum;
  244.  
  245. let _wrapNodeArray = null;
  246.  
  247. /**
  248.  * Forces XPCNativeWrapper on a DOM element. This is used only in tests.
  249.  */
  250. function wrapNode(node)
  251. {
  252.     if (!_wrapNodeArray)
  253.         _wrapNodeArray = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
  254.  
  255.     _wrapNodeArray.appendElement(node, false);
  256.     let result = _wrapNodeArray.queryElementAt(0, Ci.nsISupports);
  257.     _wrapNodeArray.removeElementAt(0);
  258.     return result;
  259. }
  260. abp.wrapNode = wrapNode;
  261.